import React, { PureComponent } from 'react';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Form, Row, Col, Input, Button, Select, DatePicker, InputNumber } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import styles from '../PateoSearchForm/style.less';
import { transferOption } from '@/support/utils';



const FormItem = Form.Item;
const { RangePicker } = DatePicker;

@connect(null, null, null, { forwardRef: true })
export default class SearchForm extends PureComponent<any, any> {

    formRef = React.createRef<FormInstance>();

    constructor(props) {
        super(props);
        this.state = {
            isExtend: props.searchVals && Object.keys(props.searchVals).length > 0 && props.isExtend, // 是否展开
        };
    }
    componentDidMount() {
        const { searchVals } = this.props;
        const { current:{ setFieldsValue }} = this.formRef;
        if (searchVals) {
            setFieldsValue({ ...searchVals });
        }
    }
    handleFormReset = () => {
        const {
            fetchParams: { type, url, extraArgs = {} },
            handleFormReset,
            dispatch,
        } = this.props;
        const { current:{ resetFields }} = this.formRef;
        resetFields();
        if (handleFormReset) {
            handleFormReset();
        }
        dispatch({
            type,
            payload: { url, ...extraArgs },
        });
    };
    onFinish = (fieldsValue) =>{
        const {
            fetchParams: { type, url, extraArgs = {} },
            saveFormValues,
            handleFieldsValue,
            dispatch,
        } = this.props;
        // 自定义数据处理方法。必须return处理之后的数据才会提交，否则不提交
        const values = handleFieldsValue ? handleFieldsValue(fieldsValue) : { ...fieldsValue };
        if (!values) return;
        // 数据为空处理
        for (let v in values) {
            if (!values[v] || !values[v].toString().trim()) {
                values[v] = undefined;
            }
        }
        // 当前的搜索条件进行保存
        if (saveFormValues) saveFormValues(values);
        dispatch({
            type,
            payload: { url, ...values, ...extraArgs },
        });
    };
    renderForm = () => {
        const { searchItems = [] } = this.props;
        const { isExtend } = this.state;
        const loopFormItems = data =>
            data.map((item, index) => {
                if (!isExtend && index > 1) {
                    return null;
                }
                const { type } = item; // 每种类型必传3属性   title  key  type
                switch (type) {
                    case 'input': {
                        const { title, key, type, rules, initialValue, ...rest } = item;
                        const placeholder = `请输入${typeof title === 'string' ? title : ''}`;
                        return (
                            <Col span={8} key={index}>
                                <FormItem name={key} label={title} rules={rules}>
                                     <Input placeholder={placeholder} allowClear {...rest} />
                                </FormItem>
                            </Col>
                        );
                    }
                    case 'select': {
                        const {
                            title,
                            key,
                            type,
                            rules,
                            initialValue,
                            selectOptions = [],
                            keyValue = ['value', 'label'],
                            showSearch = false,
                            ...rest
                        } = item;
                        const extra = showSearch
                            ? {
                                showSearch: true,
                                optionFilterProp: 'children'
                            }
                            : {};
                        return (
                            <Col span={8} key={index}>
                                <FormItem name={key} label={title} rules={rules}>
                                    <Select
                                        placeholder="请选择"
                                        allowClear
                                        getPopupContainer={triggerNode => triggerNode.parentNode}
                                        {...extra}
                                        {...rest}
                                    >
                                        {transferOption(selectOptions, keyValue)}
                                    </Select>
                                </FormItem>
                            </Col>
                        );
                    }
                    case 'datePicker': {
                        const {
                            title,
                            key,
                            type,
                            rules,
                            initialValue,
                            format = 'YYYY-MM-DD',
                            showTime = false,
                            style,
                            ...rest
                        } = item;
                        return (
                            <Col span={8} key={index}>
                                <FormItem name={key} label={title} rules={rules}>
                                    <DatePicker
                                        allowClear
                                        placeholder="请选择"
                                        showTime={showTime}
                                        showToday
                                        format={format}
                                        style={{ width: '100%', ...style }}
                                        getCalendarContainer={trigger => trigger.parentNode}
                                        {...rest}
                                    />
                                </FormItem>
                            </Col>
                        );
                    }
                    case 'inputNumber': {
                        const { title, key, type, rules,initialValue, style, ...rest } = item;
                        return (
                            <Col span={8} key={index}>
                                <FormItem name={key} label={title} rules={rules}>
                                    <InputNumber
                                        allowClear
                                        placeholder="请输入"
                                        style={{ width: '100%', ...style }}
                                        {...rest}
                                    />
                                </FormItem>
                            </Col>
                        );
                    }
                    case 'rangePicker': {
                        const {
                            title,
                            key,
                            type,
                            rules,
                            initialValue,
                            format = 'YYYY-MM-DD HH:mm:ss',
                            showTime = true,
                            style,
                            customStyle = 10,
                            ...rest
                        } = item;
                        return (
                            <Col span={customStyle} key={key}>
                                <FormItem name={key} label={title} rules={rules}>
                                    <RangePicker
                                        allowClear
                                        placeholder={['开始时间', '结束时间']}
                                        showTime={showTime}
                                        style={{ width: '100%', ...style }}
                                        format={format}
                                        getCalendarContainer={trigger => trigger.parentNode}
                                        {...rest}
                                    />
                                </FormItem>
                            </Col>
                        );
                    }
                    // rangePicker时间段选择调整样式.  时间段样式为   1个或2个必须单独占一行
                    // 例如一个时间段选择  12  6  6  两个时间段选择 12  12  0
                    // 必须保证  customStyle总和为24且必须有3个
                    case 'blank': {
                        const { key, type, customStyle = 4 } = item;
                        return (
                            <Col span={customStyle} key={index}>
                                <FormItem key={key}>
                                    { }
                                </FormItem>
                            </Col>
                        );
                    }
                }
            });
        return loopFormItems(searchItems);
    };
    // 合并初始值
    transferValue = (searchItems) =>{
        const value = {};
        searchItems.forEach(item =>{
            if(item.initialValue){
                value[item.key] = item.initialValue
            }
        });
        return value;
    };
    render() {
        const { searchItems = [], btnSize } = this.props;
        const { isExtend } = this.state;
        const initialValues = this.transferValue(searchItems);
        const offset =
            searchItems.length <= 2
                ? 16 - (searchItems.length % 3) * 8
                : isExtend
                ? 16 - (searchItems.length % 3) * 8
                : 0;
        return (
            <div className={styles.tableListForm}>
                <Form
                    ref={this.formRef}
                    onFinish={this.onFinish}
                    initialValues={initialValues}
                >
                    <Row gutter={24}>
                        {this.renderForm()}
                        <Col span={8} offset={offset}>
                          <span style={{ float: 'right' }}>
                            <Button
                                type="primary"
                                htmlType="submit"
                                size={btnSize || 'small'}
                             >
                              查询
                            </Button>
                            <Button
                                size={btnSize || 'small'}
                                style={{ marginLeft: 8 }}
                                onClick={this.handleFormReset}
                            >
                              重置
                            </Button>
                              {searchItems.length > 2 ? (
                                  <a
                                      style={{ marginLeft: 8 }}
                                      onClick={() => this.setState({ isExtend: !isExtend })}
                                  >
                                      {!isExtend ? (
                                          <span>
                                    展开 <DownOutlined />
                                  </span>
                                      ) : (
                                          <span>
                                    收起 <UpOutlined />
                                  </span>
                                      )}
                                  </a>
                              ) : null}
                          </span>
                        </Col>
                    </Row>
                </Form>
            </div>
        );
    }
}
